package com.hsmw.api.controller.integral;


import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.hsmw.api.config.jwt.CurrentHsmwUserUtils;
import com.hsmw.api.mapper.*;
import com.hsmw.api.service.*;
import com.hsmw.api.vo.DriverUserSortVo;
import com.hsmw.common.base.BaseController;
import com.htn.common.core.base.DataResponse;
import com.htn.common.core.constant.*;
import com.htn.common.core.utils.DateUtil;
import com.htn.common.core.utils.StringUtils;
import com.hsmw.domain.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tjy
 * @since 2021-07-21
 */
@Api(tags = "司机答题")
@RestController
@RequestMapping("/hsmw-driver-answer")
public class HsmwDriverAnswerController extends BaseController<HsmwDriverAnswerService, HsmwDriverAnswer> {




    final static String voiceCode = "0e7fe15a-5f6a-412f-8172-9f324d8c3bce.wav";

    final static  Long queryTime = 3L;

    @Value(value = "${sms.appKey}")
    private String appKey;
    @Value(value = "${sms.channel}")
    private String channel;
    @Value(value = "${sms.smsSign}")
    private String smsSign;
    @Value(value = "${sms.appId}")
    private int appId;
    @Value(value = "${sms.orderTemplateId}")
    private int orderTemplateId;

    @Value(value = "${sms.driverTemplateId}")
    private int driverTemplateId;

    @Value(value = "${sms.orderTimeoutNoticeBiz}")
    private int orderTimeoutNoticeBiz;

    @Value(value = "${sms.textOrderTimeOut}")
    private int textOrderTimeOut;


    @Autowired
    private HsmwOrderVehicleRelationService hsmwOrderVehicleRelationService;
    @Autowired
    private HsmwOrderVehicleRelationMapper hsmwOrderVehicleRelationMapper;
    @Autowired
    private HsmwOrderMapper hsmwOrderMapper;
    @Autowired
    private HsmwUserMapper hsmwUserMapper;
    @Autowired
    private HsmwOrderService hsmwOrderService;
    @Autowired
    private HsmwDriverNewsMapper hsmwDriverNewsMapper;
    @Autowired
    private HsmwOrderVehicleRequestMapper hsmwOrderVehicleRequestMapper;
    @Autowired
    private HsmwOrderDistributeInfoMapper hsmwOrderDistributeInfoMapper;

    @Autowired
    private HsmwOrderDistributeInfoService hsmwOrderDistributeInfoService;

    @Autowired
    private HsmwUserDriverService hsmwUserDriverService;

    @Autowired
    private HsmwVehicleMapper hsmwVehicleMapper;


    @Autowired
    private HsmwItemMapper hsmwItemMapper;


    @Autowired
    private CurrentHsmwUserUtils currentHsmwUserUtils;



    @Autowired
    private HsmwDriverAnswerService hsmwDriverAnswerService;

    @Autowired
    private HsmwUserDriverMapper hsmwUserDriverMapper;

    @Autowired
    private HsmwDriverAnswerMapper hsmwDriverAnswerMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private HsmwPointsDetailsMapper hsmwPointsDetailsMapper;



    @ApiOperation(value = "司机每日答题", notes = "司机每日答题", produces = "application/json")
    @PostMapping("findDailyAnswersInfo")
    public DataResponse findDailyAnswersInfo(){


        return new DataResponse(hsmwDriverAnswerService.findDailyAnswersInfo());
    }


    /**
     *
     * 判断答题是否正确，正确加积分，不正确 积分不变
     */
    @ApiOperation(value = "判断答题是否正确", notes = "判断答题是否正确", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "司机id",dataType = "String"),
            @ApiImplicitParam(name = "answersId",value = "题目id",dataType = "String"),
            @ApiImplicitParam(name = "button",value = "选择答案",dataType = "String"),
            @ApiImplicitParam(name = "integral",value = "积分",dataType = "Long")
    })
    @PostMapping("choiceJudgment")
    public DataResponse choiceJudgment(String id,String answersId,String button,Long integral){


        if(StringUtils.isBlank(id) || StringUtils.isBlank(answersId) || StringUtils.isBlank(button)){
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"传递参数为空");
        }

        String key = "driver:book:"+id;
        Long nowToNextDaySeconds = DateUtil.getNowToNextDaySeconds();
        Boolean flag = redisTemplate.hasKey(key);

        if(flag){
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"今天答过了");
        }

        HsmwUserDriver hsmwUserDriver = hsmwUserDriverMapper.selectById(id);
        if(hsmwUserDriver == null){
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"司机信息错误");
        }

        HsmwDriverAnswer hsmwDriverAnswer = hsmwDriverAnswerMapper.selectById(answersId);
        if(hsmwDriverAnswer == null ){
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"答题信息错误");
        }
        Map map = new HashMap();
        map.put("hsmwDriverAnswer",hsmwDriverAnswer);
        if(StringUtils.equals(button,hsmwDriverAnswer.getSelectBtn())){
            long dri = Long.parseLong(hsmwUserDriver.getDriverIntegral());
            hsmwUserDriver.setDriverIntegral(String.valueOf(dri+integral));
            hsmwUserDriverMapper.updateById(hsmwUserDriver);

            HsmwPointsDetails hsmwPointsDetails = new HsmwPointsDetails();
            hsmwPointsDetails.setTypeIntegral(new BigDecimal(integral));
            hsmwPointsDetails.setType("每日答题");
            hsmwPointsDetails.setDriverId(id);
            hsmwPointsDetailsMapper.insert(hsmwPointsDetails);
            // 答题正确 添加redis信息
            map.put("flag",true);
            redisTemplate.opsForValue().set(key,map,nowToNextDaySeconds, TimeUnit.SECONDS);
            return new DataResponse(CommonConstants.ResponseStatus.SUCCESS,"答对了");

        }else {
            // 答题错误 添加redis信息
            map.put("flag",false);
            redisTemplate.opsForValue().set(key,map,nowToNextDaySeconds, TimeUnit.SECONDS);
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"您答错了，下次努力");
        }
    }



    @ApiOperation(value = "查询判断答题状态", notes = "查询判断答题状态", produces = "application/json")
    @ApiImplicitParam(name = "司机id", value = "id", dataType = "String")
    @PostMapping("findChoiceJudgmentStatus")
    public DataResponse findChoiceJudgmentStatus(String id) {

        if(StringUtils.isBlank(id)){
            return new DataResponse(CommonConstants.ResponseStatus.FAIL,"id为空");
        }
        String key = "driver:book:"+id;

        Boolean flag = redisTemplate.hasKey(key);
        Map map = new HashMap();
        map.put("flag",flag);
        if(flag){
            Map<String,Object> hashMap = (Map<String, Object>) redisTemplate.opsForValue().get(key);
            HsmwDriverAnswer hsmwDriverAnswer = (HsmwDriverAnswer) hashMap.get("hsmwDriverAnswer");
            map.put("hsmwDriverAnswer",hsmwDriverAnswer);
            map.put("YesOrNo",hashMap.get("flag"));
            return new DataResponse(CommonConstants.ResponseStatus.SUCCESS,map);
        }
        return new DataResponse(CommonConstants.ResponseStatus.SUCCESS,map);
    }




    public static List<DriverUserSortVo> sortDriverUserSort(List<DriverUserSortVo> vos) {
        //如果选择的是
        Collections.sort(vos, new Comparator<DriverUserSortVo>() {



            @Override
            public int compare(DriverUserSortVo v1, DriverUserSortVo v2) {
                if (v2.getVehicleUnit() != (v1.getVehicleUnit())) {
                    return (v1.getVehicleUnit() - v2.getVehicleUnit());
                } else {
                    return Integer.parseInt(v2.getScore()) - Integer.parseInt(v1.getScore());
                }
            }
        });
        return vos;
    }

}

